package com.yanqu.road.entity.event;

import com.yanqu.road.utils.property.Property;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class GameObjectEvent implements IObjectEvent {

    private static Logger logger = LogManager.getLogger(GameObjectEvent.class.getName());

    private ReadWriteLock lock;
    private HashMap<Integer, IObjectEventListener> eventMap;

    public GameObjectEvent() {
        super();
        eventMap = new HashMap<>();
        lock = new ReentrantReadWriteLock(false);
    }


    @Override
    public void addListener(int eventCode, IObjectEventListener listener) {
        lock.writeLock().lock();

        eventMap.put(eventCode, listener);

        lock.writeLock().unlock();
    }

    @Override
    public void removeListener(int eventCode, IObjectEventListener listener) {
        lock.writeLock().lock();

        eventMap.remove(eventCode);

        lock.writeLock().unlock();
    }

    @Override
    public boolean notifyListener(int eventCode, int objectId) {
        lock.readLock().lock();

        IObjectEventListener iEventListener = eventMap.get(eventCode);

        lock.readLock().unlock();

        if (null != iEventListener) {
            try {
                iEventListener.triggerEvent(objectId, new EventTriggerArgs(this));
            } catch (Exception ex) {
                logger.error("事件触发异常 :" + iEventListener.getClass(), ex);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean notifyListener(int eventCode, int objectId, EventTriggerArgs eventArg) {
        lock.readLock().lock();

        IObjectEventListener iEventListener = eventMap.get(eventCode);

        lock.readLock().unlock();

        if (null != iEventListener) {
            try {
                iEventListener.triggerEvent(objectId, eventArg);
            } catch (Exception ex) {
                logger.error("事件触发异常 :" + iEventListener.getClass(), ex);
            }
            return true;
        }
        return false;
    }

    @Override
    public int checkObjectTaskComplete(int eventCode, int objectId, int taskId) {
        lock.readLock().lock();

        IObjectEventListener iEventListener = eventMap.get(eventCode);

        lock.readLock().unlock();

        if (null != iEventListener) {
            return iEventListener.checkCanComplete(objectId, taskId);
        }
        return 9997;
    }

    @Override
    public Property objectTaskFinish(int eventCode, int objectId, Integer taskId) {
        lock.readLock().lock();

        IObjectEventListener iEventListener = eventMap.get(eventCode);

        lock.readLock().unlock();

        if (null != iEventListener) {
            return iEventListener.objectTaskFinish(objectId, taskId);
        }
        return new Property();
    }
}
